'use strict';

import React, {
    Component
} from 'react';

import {
    AppRegistry,
    StyleSheet,
    Text,
    TouchableOpacity,
    View,
    Image,
} from 'react-native';

import Video from 'react-native-video';
import renderIf from './renderIf';
import Orientation from 'react-native-orientation';

export default class VideoPlayer extends Component {
    constructor(props) {
        super(props);
        this.state = {
            rate: 1,
            volume: 1,
            muted: false,
            resizeMode: 'contain',
            duration: 0.0,
            currentTime: 0.0,
            paused: false,
            payModel:false,
            opacity:0,
            btnUri:require('../../icon/btn/btn_suspend_mini.png')
        };
        this.video = Video;
    }
    componentDidMount(){
        //只允许横屏
        Orientation.lockToLandscape();
        this.video.presentFullscreenPlayer();
        // Orientation.addOrientationListener(this._orientationDidChange);
    }
    componentWillMount(){
        // const initial = Orientation.getInitialOrientation();
        // if (initial === 'PORTRAIT') {
        //     // do something
        // } else {
        //     // do something else
        // }
    }
    componentWillUnmount(){
        clearInterval(this.opacityIndex);
        clearTimeout(this.timeIndex);
        // 只允许竖屏
        Orientation.lockToPortrait();
        // Orientation.getOrientation((err, orientation) => {
        //     console.log(`Current Device Orientation: ${orientation}`);
        // });
        // // Remember to remove listener
        // Orientation.removeOrientationListener(this._orientationDidChange);
    }

    _orientationDidChange = (orientation) => {
        if (orientation === 'LANDSCAPE') {
            // 只允许竖屏
            Orientation.lockToPortrait();
        } else {
            // do something with portrait layout
        }
    }

    onLoad = (data) => {
        this.setState({duration: parseInt(data.duration)});
    }

    onProgress = (data) => {
        this.setState({currentTime: parseInt(data.currentTime)});
    }

    onEnd = () => {
        this.setState({paused: true})
        this.video.seek(0)
    }

    onAudioBecomingNoisy = () => {
        this.setState({paused: true})
    }

    onAudioFocusChanged = (event:{ hasAudioFocus: boolean }) => {
        this.setState({paused: !event.hasAudioFocus})
    }
    getCurrentTimePercentage() {
        if (this.state.currentTime > 0) {
            return parseFloat(this.state.currentTime) / parseFloat(this.state.duration);
        }
        return 0;
    }
    displayScreen(){
        if(!this.state.payModel){
            this.setState({ payModel : true });
            this.getOpacity();
        }
    }
    payControl(){
        if(this.state.paused){ // 已暂停的
            this.setState({ paused:false, btnUri:require('../../icon/btn/btn_suspend_mini.png')});
            this.hiddenControl();
        }else{
            clearInterval(this.opacityIndex);
            this.setState({ paused:true,opacity:1,btnUri:require('../../icon/btn/btn_play_mini.png') });
        }
    }
    getOpacity(){
        clearInterval(this.opacityIndex);
        this.opacityIndex = setInterval(()=>{
            if(this.state.opacity < 1){
                this.setState({opacity:1});
            }else{
                clearInterval(this.opacityIndex);
                this.timeIndex = setTimeout(()=>{
                    this.hiddenControl();
                    clearTimeout(this.timeIndex);
                },2000);
            }
        },100);
    }
    hiddenControl(){
        clearInterval(this.opacityIndex);
        this.opacityIndex = setInterval(()=>{
            if(this.state.opacity > 0){
                this.setState({opacity:this.state.opacity - 0.1})
            }else{
                clearInterval(this.opacityIndex);
                this.setState({payModel:false});
            }
        },100);
    }
    backControls(){
        this.props.navigation && this.props.navigation.goBack();
    }
    renderRateControl(rate) {
        const isSelected = (this.state.rate === rate);
        return (
            <TouchableOpacity onPress={() => { this.setState({ rate }) }}>
                <Text style={[styles.controlOption, { fontWeight: isSelected ? 'bold' : 'normal' }]}>
                    {rate}x
                </Text>
            </TouchableOpacity>
        );
    }
    renderResizeModeControl(resizeMode) {
        const isSelected = (this.state.resizeMode === resizeMode);
        return (
            <TouchableOpacity onPress={() => { this.setState({ resizeMode }) }}>
                <Text style={[styles.controlOption, { fontWeight: isSelected ? 'bold' : 'normal' }]}>
                    {resizeMode}
                </Text>
            </TouchableOpacity>
        )
    }
    renderVolumeControl(volume) {
        const isSelected = (this.state.volume === volume);
        return (
            <TouchableOpacity onPress={() => { this.setState({ volume }) }}>
                <Text style={[styles.controlOption, { fontWeight: isSelected ? 'bold' : 'normal' }]}>
                    {volume * 100}%
                </Text>
            </TouchableOpacity>
        )
    }
    render() {
        const flexCompleted = this.getCurrentTimePercentage() * 100;
        const flexRemaining = (1 - this.getCurrentTimePercentage()) * 100;
        let currentS = parseInt(this.state.currentTime % 60), currentM = parseInt(this.state.currentTime / 60);
        let durationS = parseInt(this.state.duration  % 60), durationM = parseInt(this.state.duration / 60);
        let { params } = this.props.navigation.state;
        let url = params.url;
        return (
            <View style={styles.container}>
                <TouchableOpacity
                    style={styles.fullScreen}
                    onPress={this.displayScreen.bind(this)}
                    activeOpacity={.9}>
                    <Video
                        ref={(ref: Video) => { this.video = ref }}
                        /* For ExoPlayer */
                        source={{ uri: url}}
                        // source={require('./broadchurch.mp4')}
                        style={styles.fullScreen}
                        rate={this.state.rate}
                        paused={this.state.paused}
                        volume={this.state.volume}
                        muted={this.state.muted}
                        playInBackground={ false }
                        resizeMode={this.state.resizeMode}
                        onLoad={this.onLoad}
                        onProgress={this.onProgress}
                        onEnd={this.onEnd}
                        onAudioBecomingNoisy={this.onAudioBecomingNoisy}
                        onAudioFocusChanged={this.onAudioFocusChanged}
                        repeat={false}/>
                </TouchableOpacity>
                {renderIf(this.state.payModel)(
                    <View style={[styles.fullScreen,{opacity:this.state.opacity}]}>
                        <View style={styles.payBack}>
                            <TouchableOpacity onPress={this.backControls.bind(this)}>
                                <Image source={require('../../icon/camera/camera_icon_back.png')}></Image>
                            </TouchableOpacity>
                        </View>
                        <View  style={[styles.payButton,styles.fullScreen]}>
                            <TouchableOpacity onPress={this.payControl.bind(this)}>
                                <Image source={this.state.btnUri}></Image>
                            </TouchableOpacity>
                        </View>
                    </View>
                )}
                <View style={styles.controls}>
                    <View style={styles.trackingControls}>
                        <View style={{ paddingRight:5 }}>
                            <Text style={styles.fontControls}>{currentM + ':' + (currentS > 10 ? currentS : '0'+ currentS) }</Text>
                        </View>
                        <View style={styles.progress}>
                            <View style={[styles.innerProgressCompleted, { flex: flexCompleted }]}/>
                            <View style={[styles.innerProgressRemaining, { flex: flexRemaining }]}/>
                        </View>
                        <View style={{ paddingLeft:5 }}>
                            <Text style={styles.fontControls}>{durationM + ':' + (durationS > 10 ? durationS : '0' + durationS)}</Text>
                        </View>
                    </View>
                </View>
            </View>
        );
    }
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'black',
    },
    fullScreen: {
        position: 'absolute',
        top: 0,
        left: 0,
        bottom: 0,
        right: 0,
    },
    controls: {
        backgroundColor: 'transparent',
        borderRadius: 5,
        position: 'absolute',
        bottom: 20,
        left: 20,
        right: 20,
        zIndex:3,
    },
    progress: {
        flex: 1,
        flexDirection: 'row',
        borderRadius: 3,
        overflow: 'hidden',
    },
    innerProgressCompleted: {
        height: 2,
        backgroundColor: '#cccccc',
    },
    innerProgressRemaining: {
        height: 2,
        backgroundColor: '#2C2C2C',
    },
    generalControls: {
        flex: 1,
        flexDirection: 'row',
        borderRadius: 4,
        overflow: 'hidden',
        paddingBottom: 10,
    },
    rateControl: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'center',
    },
    volumeControl: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'center',
    },
    resizeModeControl: {
        flex: 1,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
    },
    controlOption: {
        alignSelf: 'center',
        fontSize: 11,
        color: 'white',
        paddingLeft: 2,
        paddingRight: 2,
        lineHeight: 12,
    },
    fontControls:{
        fontSize:10,
        color:'white'
    },
    payButton:{
        backgroundColor:'transparent',
        position:'absolute',
        flex:1,
        justifyContent:'center',
        alignItems:'center',
        zIndex:2,
    },
    payBack:{
        zIndex:3,
        top:20,
        left:20,
    },
    trackingControls:{
        flex:1,
        flexDirection:'row',
        alignItems:'center',
    }
});